package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.query.ObjectQuery;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PermissionName;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @RequiresPermissions("role:index")
    @PermissionName("角色主页")
    @RequestMapping("index")
    public String index(Model model, @ModelAttribute("qo") ObjectQuery qo) {
        return "role/list";
    }

    @RequiresPermissions("role:list")
    @PermissionName("角色查询")
    @RequestMapping("list")
    @ResponseBody
    public PageResult<Role> list(Model model, @ModelAttribute("qo") ObjectQuery qo) {
        PageResult<Role> list = roleService.query(qo);
        return list;
    }

    @RequestMapping("queryRoleList")
    @ResponseBody
    public List<Role> queryRoleList(Model model, @ModelAttribute("qo") ObjectQuery qo) {
        List<Role> list = roleService.getAll();
        return list;
    }

    @RequestMapping("queryRoleIdsByEmpId")
    @ResponseBody
    public List<Long> queryRoleIdsByEmpId(Long empId) {
        List<Long> list = roleService.queryRoleIdsByEmpId(empId);
        return list;
    }

    @RequiresPermissions("role:delete")
    @PermissionName("角色删除")
    @RequestMapping("delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        JsonResult jsonResult = new JsonResult();
        try {
            if (id != null) {
                roleService.delete(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.markErrorMsg("删除失败");
        }
        return jsonResult;
    }

    @RequiresPermissions("role:saveOrUpdate")
    @PermissionName("角色创建更新")
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Model model, Role role,Long[] permissoinIds,
    Long[] menus) {
        JsonResult jsonResult = new JsonResult();
        try {
            if (role.getId() != null) {
                roleService.update(role,permissoinIds,menus);
            } else {
                roleService.save(role,permissoinIds,menus);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.markErrorMsg("保存或更新角色失败");
        }
        return jsonResult;
    }


}
